package app.quiz.util;

import org.antlr.stringtemplate.StringTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created with IntelliJ IDEA.
 * User: Georgiana.Scarlat
 * Date: 8/10/12
 * Time: 11:37 AM
 */
public class HTMLWriter {

    String content;

    public HTMLWriter(String content) {
        this.content = content;
    }

    private HTMLWriter wrapText(String text, String wrapping) {
        content = "<" + wrapping + ">" + "\n" + text + "\n" + "</" + wrapping + ">";
        return this;
    }

    private HTMLWriter precedeText(String text, String wrapping) {
        content = "<" + wrapping + ">" + "\n" + text;
        return this;
    }

    public HTMLWriter htmlHead() {
        return wrapText(content, "HEAD");
    }

    public HTMLWriter htmlBody() {
        return wrapText(content, "BODY");
    }

    public HTMLWriter htmlPage() {
        return wrapText(content, "html");
    }

    public HTMLWriter newLine() {
        return precedeText(content, "br");
    }

    public HTMLWriter newParagraph() {
        return wrapText(content, "P");
    }

    public HTMLWriter bold() {
        return wrapText(content, "B");
    }

    public HTMLWriter italic() {
        return wrapText(content, "I");
    }

    @Override
    public String toString() {
        return content;
    }

    public static StringTemplate getHTMLTemplate(String filename) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        String chunk;

        BufferedReader reader = new BufferedReader(new InputStreamReader(HTMLWriter.class.getClassLoader().getResourceAsStream(filename)));

        while ((chunk = reader.readLine()) != null) {
            stringBuilder.append(chunk);
        }

        return new StringTemplate(stringBuilder.toString());
    }
}
